var urlJoin = require('url-join')
var req = require('request')

var apiBaseUrl = $$config.apiBaseUrl,
    apiUsername = $$config.apiUsername,
    apiPassword = $$config.apiPassword


module.exports = {
    req: function (url, data, next) {
        req.post(urlJoin(apiBaseUrl,url), {
            auth: {
                user: apiUsername,
                pass: apiPassword
            },
            body: JSON.stringify(data)
        }, function (err, res, body) {
            if(err){
                console.log('err:')
                console.dir(err)
                console.dir(url)
                return next('request_error',null,null)
            }
            try {
                body = JSON.parse(body)
            }catch(e){
                console.dir(body)
                console.dir(url)
                return next('json_parse_err',null,null)
                //reply.redirect('/404_api')
            }
            if(body.error){
                console.dir(url)
                console.dir(body.error)
                return next(body.error,body,res)
            }
            next(null,body,res)
        })
    }
}

